import sys
from PySide6.QtWidgets import (
    QApplication,
    QMainWindow,
    QWidget,
    QVBoxLayout,
    QPushButton,
    QLineEdit,
    QLabel,
    QHBoxLayout,
)
from PySide6.QtCore import QThread, Signal, Qt
from PySide6.QtGui import QFont
from rtmp_capture import RTMPCapture
import logging


class CaptureThread(QThread):
    rtmp_url_signal = Signal(str)
    stream_key_signal = Signal(str)
    error_signal = Signal(str)

    def __init__(self):
        super().__init__()
        self.capture = RTMPCapture()
        self.capture.logger = logging.getLogger(__name__)

        def log_rtmp_url(url):
            self.rtmp_url_signal.emit(url)

        def log_stream_key(key):
            self.stream_key_signal.emit(key)

        def log_error(error):
            self.error_signal.emit(error)

        self.capture.on_rtmp_url = log_rtmp_url
        self.capture.on_stream_key = log_stream_key
        self.capture.on_error = log_error

    def run(self):
        self.capture.start_capture(
            filter_str="tcp port 1935 or tcp port 80 or tcp port 443"
        )


class StyledButton(QPushButton):
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setStyleSheet("""
            QPushButton {
                background-color: #6B5B95;
                color: white;
                border: none;
                padding: 5px 15px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #8677AD;
            }
            QPushButton:pressed {
                background-color: #574B7C;
            }
            QPushButton:disabled {
                background-color: #CCCCCC;
            }
        """)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("推流码抓取")
        self.setMinimumWidth(700)
        self.setMinimumHeight(350)
        self.setStyleSheet("""
            QMainWindow {
                background-color: #F5F5F5;
            }
            QLabel {
                font-size: 14px;
                color: #333333;
            }
            QLineEdit {
                padding: 8px;
                border: 1px solid #CCCCCC;
                border-radius: 4px;
                background-color: white;
                selection-background-color: #6B5B95;
                font-size: 13px;
            }
            QLineEdit:read-only {
                background-color: #F8F8F8;
            }
        """)

        # 创建主窗口部件和布局
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        layout = QVBoxLayout(main_widget)
        layout.setSpacing(20)
        layout.setContentsMargins(30, 30, 30, 30)

        # 标题
        title_label = QLabel("推流码抓取")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("""
            font-size: 24px;
            color: #6B5B95;
            font-weight: bold;
            margin-bottom: 20px;
        """)
        layout.addWidget(title_label)

        # 创建开始抓包按钮
        self.start_button = StyledButton("开始抓取")
        self.start_button.clicked.connect(self.toggle_capture)
        self.start_button.setFixedHeight(45)
        self.start_button.setFont(QFont("", 14))
        layout.addWidget(self.start_button)

        # 服务器地址
        server_layout = QHBoxLayout()
        server_label = QLabel("服务器:")
        server_label.setFixedWidth(80)
        self.server_edit = QLineEdit()
        self.server_edit.setReadOnly(True)
        self.copy_server_btn = StyledButton("复制")
        self.copy_server_btn.setFixedWidth(80)
        self.copy_server_btn.clicked.connect(
            lambda: self.copy_to_clipboard(self.server_edit.text())
        )

        server_layout.addWidget(server_label)
        server_layout.addWidget(self.server_edit)
        server_layout.addWidget(self.copy_server_btn)
        layout.addLayout(server_layout)

        # 推流码
        stream_layout = QHBoxLayout()
        stream_label = QLabel("推流码:")
        stream_label.setFixedWidth(80)
        self.stream_edit = QLineEdit()
        self.stream_edit.setReadOnly(True)
        self.copy_stream_btn = StyledButton("复制")
        self.copy_stream_btn.setFixedWidth(80)
        self.copy_stream_btn.clicked.connect(
            lambda: self.copy_to_clipboard(self.stream_edit.text())
        )

        stream_layout.addWidget(stream_label)
        stream_layout.addWidget(self.stream_edit)
        stream_layout.addWidget(self.copy_stream_btn)
        layout.addLayout(stream_layout)

        # 错误信息
        self.error_label = QLabel()
        self.error_label.setStyleSheet("""
            color: #D32F2F;
            font-size: 13px;
            padding: 10px;
            background-color: #FFEBEE;
            border-radius: 4px;
        """)
        self.error_label.setWordWrap(True)
        self.error_label.hide()  # 默认隐藏错误标签
        layout.addWidget(self.error_label)

        # 添加弹性空间
        layout.addStretch()

        # 初始化抓包线程
        self.capture_thread = None
        self.is_capturing = False

    def toggle_capture(self):
        if not self.is_capturing:
            self.start_capture()
        else:
            self.stop_capture()

    def start_capture(self):
        self.is_capturing = True
        self.start_button.setText("停止抓取")
        self.error_label.hide()  # 隐藏错误信息
        self.capture_thread = CaptureThread()
        self.capture_thread.rtmp_url_signal.connect(self.update_server)
        self.capture_thread.stream_key_signal.connect(self.update_stream_key)
        self.capture_thread.error_signal.connect(self.show_error)
        self.capture_thread.start()

    def stop_capture(self):
        if self.capture_thread:
            self.capture_thread.terminate()
            self.capture_thread.wait()
        self.is_capturing = False
        self.start_button.setText("开始抓取")

    def update_server(self, url):
        self.server_edit.setText(url)

    def update_stream_key(self, key):
        self.stream_edit.setText(key)

    def show_error(self, error):
        self.error_label.setText(f"错误: {error}")
        self.error_label.show()  # 显示错误标签

    def copy_to_clipboard(self, text):
        if text.strip():  # 只在有内容时复制
            clipboard = QApplication.clipboard()
            clipboard.setText(text)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用程序级别的字体
    app.setFont(QFont("", 12))
    
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
